package cn.redragon.soa.common.util;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@UtilityClass
public class FileUtil {

    @SneakyThrows
    public void copy(InputStream inputStream, String target) {
        try {
            Files.createDirectories(Paths.get(target).getParent());
            Files.copy(inputStream, Paths.get(target), StandardCopyOption.REPLACE_EXISTING);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    @SneakyThrows
    public void copy(File source, File target, Boolean deleteSource) {
        boolean isLinux = System.getProperty("os.name").toLowerCase().startsWith("linux");
        log.info("Current OS is {}", System.getProperty("os.name"));
        Files.createDirectories(target.getParentFile().toPath());
        if (isLinux) {
            ProcessBuilder builder = new ProcessBuilder();
            String cpCmd = String.format("cp %s %s", source.toPath(), target.toPath());
            builder.command("sh", "-c", cpCmd);
            long start = System.currentTimeMillis();
            int exitCode = builder.inheritIO().start().waitFor();
            log.info("cp {} to {} finished with exit code={}, duration={}s", source.toPath(), target.toPath(), exitCode, (System.currentTimeMillis() - start) / (double) 1000);
        } else {
            Files.copy(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

        if (deleteSource) {
            Files.deleteIfExists(source.toPath());
        }
    }
}
